#!/usr/bin/env python

#min_x = min([min(line.get_xdata()) for line in self.axes.lines])
#        max_x = max([max(line.get_xdata()) for line in self.axes.lines])           
#        self.axes.set_xlim(min_x,max_x)

import sys

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from plotDataClass import LPC
from matplotlib.lines import Line2D

import ui_Plot_Options

#markers = {0: '_draw_tickleft', 1: '_draw_tickright', 2: '_draw_tickup', 
#3: '_draw_tickdown', 4: '_draw_caretleft', 5: '_draw_caretright', 
#filled_markers = ('o', '^', 'v', '<', '>', 's', 'd', 'D', 'h', 'H', 'p')

line_styles = dict(Solid = '-',\
                    Dashed = '--', \
                    DashDot = '-.',\
                    Dotted = ':',\
                    Steps = 'steps', \
                    none = 'None')

marker_styles = dict(none = 'None',\
                    circles = 'o',\
                    triangle_up = '^',\
                    triangle_down  = 'v',\
                    triangle_left  = '<',\
                    triangle_right  = '>',\
                    square  = 's',\
                    plus  = '+',\
                    cross  = 'x',\
                    diamond  = 'D',\
                    thin_diamond  = 'd',\
                    tripod_down  = '1',\
                    tripod_up  = '2',\
                    tripod_left  = '3',\
                    tripod_right  = '4',\
                    hexagon  = 'h',\
                    rotated_hexagon  = 'H',\
                    pentagon  = 'p',\
                    vertical_line  = '|',\
                    horizontal_line  = '_',\
                    dots = '.')


class Plot_Options_Dialog(QDialog, ui_Plot_Options.Ui_Plot_Options_Dialog):
    def __init__(self, activeTraces = None, errorTraces = None,  parent = None):
        super(Plot_Options_Dialog, self).__init__(parent)
        self.setupUi(self)
        
        self.plotTitle = "Plot Title"
        self.xmin = 0.0
        self.xmax = 10.0
        self.xtitle = "X-Axis"
        
        self.ymin = 0.0
        self.ymax = 20.0
        self.ytitle = "Y-Axis"
        self.activeplots = activeTraces
        self.errorplots = errorTraces
                

        self.connect(self.activePlotListWidget, SIGNAL("itemClicked(QListWidgetItem *)"), self.getPlotItem)
        self.connect(self.mstyle_comboBox, SIGNAL("currentIndexChanged(QString)"), self.setMStyle)
        self.connect(self.ms_spinBox, SIGNAL("valueChanged(double)"), self.setMSize)
        self.connect(self.lstyle_comboBox, SIGNAL("currentIndexChanged(QString)"), self.setLStyle)
        self.connect(self.lw_spinBox, SIGNAL("valueChanged(double)"), self.setLWidth)
        self.connect(self.lineColorBtn, SIGNAL("colorChanged(QColor)"), self.setLColor) 
        self.connect(self.markerColorBtn, SIGNAL("colorChanged(QColor)"), self.setMColor) 
        
        self.populate_dialog()
        
    def setMSize(self, value):
        #print "Set Marker Size"
        if self.activePlotListWidget.currentItem():
            activeLinePlot = self.getPlotItem(self.activePlotListWidget.currentItem())
            activeLinePlot.set_markersize(value)
            self.setupLineOptions(activeLinePlot)
        
    def setMStyle(self, value):
        #print "Set Marker Style"
        if self.activePlotListWidget.currentItem():
            activeLinePlot = self.getPlotItem(self.activePlotListWidget.currentItem())
            activeLinePlot.set_marker(marker_styles.get(str(value)))#need to set value to str as it is QString
            self.setupLineOptions(activeLinePlot)
    
    def setMColor(self, QColor):
        if self.activePlotListWidget.currentItem():
            activeLinePlot = self.getPlotItem(self.activePlotListWidget.currentItem())
            #print str(QColor.name())
            activeLinePlot.set_markerfacecolor(str(QColor.name()))#need to set value to str as it is QString
            self.setupLineOptions(activeLinePlot)
        
    def setLWidth(self, value):
        #print "Set L Width"
        if self.activePlotListWidget.currentItem():
            activeLinePlot = self.getPlotItem(self.activePlotListWidget.currentItem())
            activeLinePlot.set_linewidth(value)
            self.setupLineOptions(activeLinePlot)
    
    def setLStyle(self, value):
        #print "Set Line Style"
        if self.activePlotListWidget.currentItem():
            activeLinePlot = self.getPlotItem(self.activePlotListWidget.currentItem())
            activeLinePlot.set_linestyle(line_styles.get(str(value)))#need to set value to str as it is QString
            self.setupLineOptions(activeLinePlot)
            
    def setLColor(self, QColor):
        if self.activePlotListWidget.currentItem():
            activeLinePlot = self.getPlotItem(self.activePlotListWidget.currentItem())
            #print str(QColor.name())
            activeLinePlot.set_color(str(QColor.name()))#need to set value to str as it is QString
            self.setupLineOptions(activeLinePlot)
            
            errorlist = self.getErrorItem(self.activePlotListWidget.currentItem())
            if errorlist:
                for list in errorlist:
                    for item in list:
                        item.set_color(str(QColor.name()))
    
    def getErrorItem(self, item):
        errorItem = self.errorplots.get(str(item.text()))
        return errorItem
        
    def getPlotItem(self, item):
        linePlotItem = self.activeplots.get(str(item.text()))
        self.setupLineOptions(linePlotItem)
        return linePlotItem
            
    def getKey(self, dict, value):
        for key, val in dict.items():
            if val == value:
                return key
                
    
    def setupLineOptions(self, lineInstance):
        
        match_index = self.mstyle_comboBox.findText(self.getKey(marker_styles, lineInstance.get_marker()))
        self.mstyle_comboBox.setCurrentIndex(match_index)
        
        ls = lineInstance.get_linestyle()
        key = self.getKey(line_styles, lineInstance.get_linestyle())
        
        match_index = self.lstyle_comboBox.findText(str(key))
        self.lstyle_comboBox.setCurrentIndex(match_index)
        
        self.lw_spinBox.setValue(lineInstance.get_linewidth())
        self.ms_spinBox.setValue(lineInstance.get_markersize())
        
        if lineInstance.get_color() is None:
            pass
        else:
            lcolor = QColor(lineInstance.get_color())
            self.lineColorBtn.setColor(lcolor)
        
        if lineInstance.get_markerfacecolor() is None:
            pass
        else:
            mcolor = QColor(lineInstance.get_markerfacecolor())
            self.markerColorBtn.setColor(mcolor)
            
    def getPlotDict(self, activeTraces):#takes a list of LinePlotClasses
        tuple_list = []
        if activeTraces:
            for item in activeTraces.__iter__():
                tuple_list.append((item.label, item))
        
        return dict(tuple_list)
            
            
    def getColor(self):    
        color = QColorDialog.getColor(Qt.blue, self)
        if color.isValid(): 
            print color.name()
            #self.colorLabel.setText(color.name())
            #self.colorLabel.setPalette(QtGui.QPalette(color))
    
            
    def populate_dialog(self):
        #populate first tab
        self.plottitle_lineEdit.setText(self.plotTitle)
        
        self.xmin_lineEdit.setText(str(self.xmin))
        self.xmax_lineEdit.setText(str(self.xmax))
        self.xlabel_lineEdit.setText(self.xtitle)
        
        self.ymin_lineEdit.setText(str(self.ymin))
        self.ymax_lineEdit.setText(str(self.ymax))
        self.ylabel_lineEdit.setText(self.ytitle)
        
        #populate second tab
        self.lstyle_comboBox.addItems(line_styles.keys())
        self.mstyle_comboBox.addItems(marker_styles.keys())
        if self.activeplots is not None and type(self.activeplots) is dict:
            activeList = self.activeplots.keys()
            activeList.sort()
            self.activePlotListWidget.addItems(activeList)
        self.activePlotListWidget.setCurrentRow(0)
        self.getPlotItem(self.activePlotListWidget.currentItem())
        
        
        
        
    
    
    
if __name__ == "__main__":
    dialog = QApplication(sys.argv)
    mydialog = Plot_Options_Dialog()
    mydialog.show()
    sys.exit(dialog.exec_())
